// src/utils/request.ts
import { ElMessage } from 'element-plus'

// 基础配置
const BASE_URL = import.meta.env.VITE_APP_BASE_API || ''
const DEFAULT_HEADERS = {
    'Content-Type': 'application/json;charset=utf-8'
}

// 全局错误处理
function handleError(error: any) {
    console.error('请求出错:', error)
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
}

// 构建完整 URL
function buildUrl(url: string): string {
    return url.startsWith('http') ? url : `${BASE_URL}${url}`
}

// 处理响应
async function handleResponse(response: Response) {
    if (!response.ok) {
        const errText = await response.text()
        throw new Error(`HTTP ${response.status} - ${errText}`)
    }

    const contentType = response.headers.get('content-type')

    // 判断是否是 JSON 格式
    if (contentType?.includes('application/json')) {
        return response.json()
    }

    // ✅ 新增：判断是否是 SSE 类型
    if (contentType?.includes('text/event-stream')) {
        return response.body
    }

    // 如果是流式响应，返回 ReadableStream
    if (contentType?.includes('text/plain') || contentType?.includes('application/octet-stream')) {
        return response.body
    }

    return response.text()
}

function fetchWithTimeout(url: string, options: RequestInit = {}, timeout = 100000) {
    return Promise.race([
        fetch(url, options),
        new Promise<never>((_, reject) =>
            setTimeout(() => reject(new Error('请求超时')), timeout)
        )
    ])
}

// 创建统一请求函数
export default {
    async get<T>(url: string, options: RequestInit = {}): Promise<T> {
        const config: RequestInit = {
            ...options,
            method: 'GET',
            headers: { ...DEFAULT_HEADERS, ...(options.headers || {}) }
        }

        try {
            const res = await fetch(buildUrl(url), config)
            return await handleResponse(res)
        } catch (error) {
            return handleError(error)
        }
    },

    async post<T>(url: string, data: any, options: RequestInit = {}): Promise<T> {
        const config: RequestInit = {
            ...options,
            method: 'POST',
            headers: { ...DEFAULT_HEADERS, ...(options.headers || {}) },
            body: JSON.stringify(data)
        }

        try {
            const res = await fetch(buildUrl(url), config)
            return await handleResponse(res)
        } catch (error) {
            return handleError(error)
        }
    },

    // 流式请求方法（用于接收大模型输出）
    async postStream(url: string, data: any, options: RequestInit = {}) {
        const config: RequestInit = {
            ...options,
            method: 'POST',
            headers: {
                ...DEFAULT_HEADERS,
                ...(options.headers || {}),
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }

        try {
            const response = await fetchWithTimeout(buildUrl(url), config)

            if (!response.ok) {
                const text = await response.text()
                ElMessage.error(text || '请求失败')
                throw new Error(text)
            }

            return response.body // 返回 ReadableStream
        } catch (error) {
            return handleError(error)
        }
    }
}